#include "ohos_rtp_receiver.h"
#include "ohos_media_track.h"
#include "ohos_media_stream.h"
#include "ohos_audio_track.h"
#include "ohos_video_track.h"
#include <vector>

namespace ohoswebrtc {

OHOSRtpReceiver::OHOSRtpReceiver(
    rtc::scoped_refptr<webrtc::RtpReceiverInterface> rtp_receiver, rtc::scoped_refptr<OHOSPeerConnectionFactoryInterface> peer_connection_factory)
    : rtp_receiver_(rtp_receiver),
      peer_connection_factory_(peer_connection_factory) {
  RTC_LOG(LS_INFO) << __FUNCTION__ << ": Ctor";
}

rtc::scoped_refptr<OHOSMediaTrackInterface> OHOSRtpReceiver::track() const {  
  rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track =
      rtp_receiver_->track();
  if (!track) {
    return rtc::scoped_refptr<OHOSMediaTrackInterface>();
  }
  if (track->kind() == webrtc::MediaStreamTrackInterface::kVideoKind) {
    return rtc::scoped_refptr<OHOSMediaTrackInterface>(new rtc::RefCountedObject<OHOSVideoTrack>(
      rtc::scoped_refptr<webrtc::VideoTrackInterface>(
            static_cast<webrtc::VideoTrackInterface*>(track.get())), peer_connection_factory_));
  } else if (track->kind() == webrtc::MediaStreamTrackInterface::kAudioKind) {
    return rtc::scoped_refptr<OHOSMediaTrackInterface>(new rtc::RefCountedObject<OHOSAudioTrack>(
        rtc::scoped_refptr<webrtc::AudioTrackInterface>(
            static_cast<webrtc::AudioTrackInterface*>(track.get())), peer_connection_factory_));
  }
  return rtc::scoped_refptr<OHOSMediaTrackInterface>();
}

std::vector<rtc::scoped_refptr<OHOSMediaStreamInterface>> OHOSRtpReceiver::streams() const {
  std::vector<rtc::scoped_refptr<OHOSMediaStreamInterface>> streams;
  for (rtc::scoped_refptr<webrtc::MediaStreamInterface> stream : rtp_receiver_->streams()) {
    streams.push_back(rtc::scoped_refptr<OHOSMediaStreamInterface>(new rtc::RefCountedObject<OHOSMediaStream>(stream, peer_connection_factory_)));
  }
  return streams;
}

void OHOSRtpReceiver::SetJitterBufferMinimumDelay(double delay_seconds) {
  rtp_receiver_->SetJitterBufferMinimumDelay(delay_seconds);
}

void OHOSRtpReceiver::RegisterObserver(OHOSRtpReceiverObserver* observer) {
  RTC_DCHECK(observer);
  observer_ = observer;
  if (observer != nullptr) {
    rtp_receiver_->SetObserver(this);
  }
}

void OHOSRtpReceiver::OnFirstPacketReceived(cricket::MediaType media_type) {
  if (nullptr != observer_) {
    observer_->OnFirstPacketReceived(media_type);
  }
}

OHOSRtpReceiver::~OHOSRtpReceiver() {
  RTC_LOG(LS_INFO) << __FUNCTION__ << ": Dtor";
}



}  // namespace ohoswebrtc